package org.dingyom.gift.service.impl;

import org.apache.commons.lang.StringUtils;
import org.dingyom.gift.constants.SmsContants;
import org.dingyom.gift.dto.SmsDto;
import org.dingyom.gift.exception.asserts.Assert;
import org.dingyom.gift.exception.code.StatusCode;
import org.dingyom.gift.properties.SmsProperties;
import org.dingyom.gift.service.ISmsService;
import org.dingyom.gift.util.AjaxResult;
import org.dingyom.gift.util.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements ISmsService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SmsProperties properties;
    //发送验证码
    @Override
    public AjaxResult sendSms(String tel) {
        //判断短信验证码是否存在 redis中 保存格式设置成 code:time  验证码和生成时间
        String key = SmsContants.SMSCODE_KEY + tel;
        String smsCodeOfRedis = (String)redisTemplate.opsForValue().get(key);
        String code = "";
        if (StringUtils.isEmpty(smsCodeOfRedis)) {//不存在就产生新的
            code = StrUtils.getRandomString(6);
        }else {//存在 就用存在的
            //判断两次发送验证码过了重发时间没 没过就可能是恶意请求 报错
            code = smsCodeOfRedis.split(":")[0];
            String time = smsCodeOfRedis.split(":")[1];
            if (System.currentTimeMillis()-new Date(Long.valueOf(time)).getTime() <= 60*1000*properties.getResendTime()){//60*1000
                return AjaxResult.me().setSuccess(false).setCode(500).setMessage("非法请求，请勿乱搞！");
            }
        }
        //将验证码记录进redis
        redisTemplate.opsForValue().set(key, code+":"+System.currentTimeMillis(),properties.getExpireTime(), TimeUnit.MINUTES);

        //调用短信接口发送验证码 %s 占位符
        String content = String.format("您的验证码为%s，请在%s分钟之内使用！",code,properties.getExpireTime());
//        SmsUtil.sendSms(mobile, content);

        System.out.println(content);
        return AjaxResult.me();
    }

    //校验验证码
    @Override
    public AjaxResult verify(SmsDto dto) {
        String tel = dto.getTel();
        String sms = dto.getSms();
        //获取redis中的验证码
        String key = SmsContants.SMSCODE_KEY + tel;
        String smsCodeOfRedis = (String)redisTemplate.opsForValue().get(key);
        //判断redis中是否有这个验证码
        Assert.isNotEmpty(smsCodeOfRedis, StatusCode.CODE_400_SMSCODE_EXSIT);
        //redis中的验证码
        String smsCode = smsCodeOfRedis.split(":")[0];
        //比对验证码
        Assert.equalsIgnoreCase(smsCode,sms,StatusCode.CODE_500_SMS_VERIFY_EXSIT);

        //验证码用过后 就要删除掉 防止恶意调用这个
        redisTemplate.delete(key);
        return AjaxResult.me();
    }
}
